package com.sixseven.controller;

import com.sixseven.bean.Cart;
import com.sixseven.bean.CartItem;
import com.sixseven.service.CowryService;
import com.sixseven.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Belly
 * @version 1.1.0
 */
@RestController
@Slf4j
public class CartController {
    @Resource
    private CowryService cowryService;
    @RequestMapping("/addCartItem")
    public Result addCartItem(@RequestBody CartItem cartItem, HttpServletRequest request){
        CartItem cartCartItem = new CartItem(cartItem.getId(),
                cowryService.getById(cartItem.getId()).getName(),
                1, cartItem.getPrice(), cartItem.getPrice(), cartItem.getImgPath());
        Cart sessionCart = (Cart) request.getSession().getAttribute("cart");
        if (sessionCart == null) {
            sessionCart = new Cart();
            request.getSession().setAttribute("cart", sessionCart);
        }
        sessionCart.addItem(cartCartItem);
        return Result.success("200", "添加成功");
    }
    @PostMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        Cart sessionCart = (Cart) request.getSession().getAttribute("cart");
        if (sessionCart == null){
            return Result.error();
        }
        if (sessionCart.getCartItemMap().size() == 0){
            return Result.error("440", "购物车空荡荡", null);
        }
        return Result.success(sessionCart);
    }
    @GetMapping("/modify")
    public Result modify(@RequestParam Integer id, @RequestParam Integer count, HttpServletRequest request){
        if (id == null){
            return Result.error();
        }
        if (count == null){
            return Result.error();
        }
        Cart sessionCart = (Cart) request.getSession().getAttribute("cart");
        if (sessionCart == null){
            return Result.error();
        }
        sessionCart.modifyItem(id, count);
        return Result.success("200", null);
    }
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id, HttpServletRequest request){
        if (id == null){
            return Result.error();
        }
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null){
            return Result.error();
        }
        cart.deleteItem(id);
        return Result.success("200", "删除成功");
    }
}
